/**
 * 
 */
package com.mc.data;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.hutool.extra.pinyin.PinyinUtil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * @author w.weizhen
 * 
 * 全国统计用区划代码和城乡划分代码
 * 
 * 行政区划代码
 * 
 * 数据生成和处理
 * 
 */
public class Xzqhdm {
    
    private static final String readPath = "D:\\文件\\日期文件\\202207081\\read\\";
    
    private static final String writePath = "D:\\文件\\日期文件\\202207081\\write\\";
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        
        //wholeCountry();//处理信息
        
        //测试获取地理坐标
        //System.out.println(getCoordinate("河北省石家庄市长安区建北街道青园街道"));
        
    	
    	arrange();//文件整理
    	
    }
    
    // 处理 全国统计用区划代码和城乡划分代码 json文件 信息
    private static void wholeCountry()
    {
        // 每一个省是一个对象
        //String file = "area_3L.json";
        //String file = "area_4L.json";
        String file = "area_5L.json";
        JSONArray shengs = read(readPath + file);
        
        //循环处理每一个省份数据，生成各个省、市、区文件
        for(int i = 0; i < shengs.size(); i++) 
        {
            //整理后的省数据，省名pinyin.json文件
            JSONObject sheng_data = new JSONObject();
            JSONArray shis_data = new JSONArray();
            
            //省原始数据
            JSONObject sheng = shengs.getJSONObject(i);
            //生成名称信息
            String sheng_name = sheng.getString("name");
            String sheng_pinyin = PinyinUtil.getPinyin(sheng_name, "");//指定分隔符
            System.out.println(sheng_name + "   " + sheng_pinyin);
            
            //数据是否已经被处理，已经被处理不再向下执行
            File directory = new File(writePath + sheng_pinyin);
            if (directory.exists()  && directory.isDirectory()) 
            {
                continue;
            }
            
            //市数据
            JSONArray shis = sheng.getJSONArray("children");
            for (int j = 0; j < shis.size(); j++) 
            {
                //整理后的省数据，省名pinyin.json文件
                JSONObject shi_data = new JSONObject();
                JSONArray qus_data = new JSONArray();
                
                //市信息
                JSONObject shi = shis.getJSONObject(j);
                //区信息
                JSONArray qus = shi.getJSONArray("children");
                
                //生成名称信息
                String shi_name = shi.getString("name");
                String shi_pinyin = PinyinUtil.getPinyin(shi_name, "");//指定分隔符
                System.out.println(shi_name + "   " + shi_pinyin);
                
                //市信息，单独生成文件
                JSONObject sheng_child = new JSONObject();
                sheng_child.put("name", shi_name);
                sheng_child.put("key", shi_pinyin);
                sheng_child.put("level", 3);
                sheng_child.put("districtCode", shi.getString("code"));
                sheng_child.put("core", getCoordinate(sheng_name+shi_name));
                sheng_child.put("childNum", qus.size());
                sheng_child.put("boundaries", new JSONArray());
                shis_data.add(sheng_child);
                
                for (int k = 0; k < qus.size(); k++) 
                {
                    //整理后的省数据，省名pinyin.json文件
                    JSONObject qu_data = new JSONObject();
                    JSONArray jiedaos_data = new JSONArray();
                    
                    //区信息
                    JSONObject qu = qus.getJSONObject(k);
                    //街道信息
                    JSONArray jiedaos = qu.getJSONArray("children");
                    
                    //生成名称信息
                    String qu_name = qu.getString("name");
                    String qu_pinyin = PinyinUtil.getPinyin(qu_name, "");//指定分隔符
                    System.out.println(qu_name + "   " + qu_pinyin);
                    
                    //区信息，单独生成文件
                    JSONObject shi_child = new JSONObject();
                    shi_child.put("name", qu_name);
                    shi_child.put("key", qu_pinyin);
                    shi_child.put("level", 4);
                    shi_child.put("districtCode", qu.getString("code"));
                    shi_child.put("core", getCoordinate(sheng_name+shi_name+qu_name));
                    shi_child.put("childNum", jiedaos.size());
                    shi_child.put("boundaries", new JSONArray());
                    qus_data.add(shi_child);
                    
                    //区信息，包含街道、居委会信息
                    qu_data.put("name", qu_name);
                    qu_data.put("key", qu_pinyin);
                    qu_data.put("level", 4);
                    qu_data.put("districtCode", qu.getString("code"));
                    qu_data.put("core", getCoordinate(sheng_name+shi_name+qu_name));
                    qu_data.put("childNum", jiedaos.size());
                    qu_data.put("boundaries", new JSONArray());
                    
                    for (int l = 0; l < jiedaos.size(); l++) 
                    {
                        //整理后的省数据，省名pinyin.json文件
                        JSONArray juweihuis_data = new JSONArray();
                        
                        //街道信息
                        JSONObject jiedao = jiedaos.getJSONObject(l);
                        //居委会信息
                        JSONArray juweihuis = jiedao.getJSONArray("children");
                        //生成名称信息
                        String jiedao_name = jiedao.getString("name");
                        String jiedao_pinyin = PinyinUtil.getPinyin(jiedao_name, "");//指定分隔符
                        
                        //街道信息，包含居委会信息
                        JSONObject qu_child = new JSONObject();
                        qu_child.put("name", jiedao_name);
                        qu_child.put("key", jiedao_pinyin);
                        qu_child.put("level", 5);
                        qu_child.put("districtCode", jiedao.getString("code"));
                        qu_child.put("core", getCoordinate(sheng_name+shi_name+qu_name+jiedao_name));
                        qu_child.put("childNum", juweihuis.size());
                        qu_child.put("boundaries", new JSONArray());
                        
                        for (int m = 0; m < juweihuis.size(); m++) 
                        {
                            //居委会信息
                            JSONObject juweihui = juweihuis.getJSONObject(m);
                            //生成名称信息
                            String juweihui_name = juweihui.getString("name");
                            String juweihui_pinyin = PinyinUtil.getPinyin(juweihui_name, "");//指定分隔符
                            
                            //居委会信息
                            JSONObject juweihui_data = new JSONObject();
                            juweihui_data.put("name", juweihui_name);
                            juweihui_data.put("key", juweihui_pinyin);
                            juweihui_data.put("level", 6);
                            juweihui_data.put("districtCode", juweihui.getString("code"));
                            juweihui_data.put("core", getCoordinate(sheng_name+shi_name+qu_name+jiedao_name+juweihui_name));
                            juweihui_data.put("boundaries", new JSONArray());
                            juweihuis_data.add(juweihui_data);
                        }
                        qu_child.put("childs", juweihuis_data);
                        jiedaos_data.add(qu_child);
                    }
                    
                    //生成文件
                    qu_data.put("childs", jiedaos_data);
                    write(writePath+sheng_pinyin+"\\"+shi_pinyin+"\\"+qu_pinyin+".json", qu_data.toJSONString());
                }
                
                //生成文件
                shi_data.put("childs", qus_data);
                write(writePath+sheng_pinyin+"\\"+shi_pinyin+"\\"+shi_pinyin+".json", shi_data.toJSONString());
            }
            
            //生成文件
            sheng_data.put("childs", shis_data);
            write(writePath+sheng_pinyin+"\\"+sheng_pinyin+".json", sheng_data.toJSONString());
        }
    }
    
    // 调用百度地图API根据地址，获取坐标
    private static JSONObject getCoordinate(String address) {
        JSONObject core = new JSONObject();
        if (address != null && !"".equals(address)) {
            String AK = "0vBPXOSY1nLFwvBvVnrixqnv";
            address = address.replaceAll("\\s*", "").replace("#", "栋");
            String url = "http://api.map.baidu.com/geocoder/v2/?address=" + address + "&output=json&ak=" + AK;
            String json = loadJSON(url);
            if (json != null && !"".equals(json)) {
                // JSONObject obj = JSONObject.fromObject(json);
                JSONObject obj = JSON.parseObject(json);
                if ("0".equals(obj.getString("status"))) {
                    double lng = obj.getJSONObject("result").getJSONObject("location").getDouble("lng"); // 经度
                    double lat = obj.getJSONObject("result").getJSONObject("location").getDouble("lat"); // 纬度
                    core.put("lng", lng);
                    core.put("lat", lat);
                    return core;
                }
            }
        }
        //没有得到坐标点，等待发现
        if(core == null || core.isEmpty())
        {
            System.err.println(address);
            try {
                Thread.sleep(60000);
            } catch (Exception e) {
                // TODO: handle exception
            }
            
        }
        return core;
    }
    
    private static String loadJSON(String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "UTF-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
        return json.toString();
    }
    
    
    private static void arrange()
    {
    	String source = "D:/文件/日期文件/202207200/source/";//源件目录
    	String target = "D:/文件/日期文件/202207200/target/";//目标目录
    	
    	List<String> paths = recursion(source);
    	for (int i = 0; i < paths.size(); i++) 
    	{
    		try {
    			String path = paths.get(i);
    			//读取本地json文件，转为json集合
                String json=FileUtils.readFileToString(new File(path), "UTF-8");
                JSONObject data = JSON.parseObject(json);
                //datas = JSON.parseArray(fastjson);
                //parse(data);
                //System.out.println(data.toJSONString());
                if (data.containsKey("core")) 
                {
                	JSONObject core = data.getJSONObject("core");
                    JSONArray cp = new JSONArray();
                    cp.add(core.getString("lng"));
                    cp.add(core.getString("lat"));
                    data.put("cp", cp);
                    data.remove("core");
				}
                if (data.containsKey("childs")) 
                {
                	JSONArray childs0 = data.getJSONArray("childs");
                	for (int j = 0; j < childs0.size(); j++) 
                	{
                		JSONObject child0 = childs0.getJSONObject(j);
                		if (child0.containsKey("core")) 
                        {
                        	JSONObject core = child0.getJSONObject("core");
                            JSONArray cp = new JSONArray();
                            cp.add(core.getString("lng"));
                            cp.add(core.getString("lat"));
                            child0.put("cp", cp);
                            child0.remove("core");
        				}
                		
                		if (child0.containsKey("childs")) 
                        {
                			JSONArray childs1 = child0.getJSONArray("childs");
                			for (int k = 0; k < childs1.size(); k++) 
                			{
                				JSONObject child1 = childs1.getJSONObject(k);
                        		if (child1.containsKey("core")) 
                                {
                                	JSONObject core = child1.getJSONObject("core");
                                    JSONArray cp = new JSONArray();
                                    cp.add(core.getString("lng"));
                                    cp.add(core.getString("lat"));
                                    child1.put("cp", cp);
                                    child1.remove("core");
                				}
                        		
                        		if (child1.containsKey("childs")) 
                                {
                        			JSONArray childs2 = child1.getJSONArray("childs");
                        			for (int l = 0; l < childs2.size(); l++) 
                        			{
                        				JSONObject child2 = childs2.getJSONObject(l);
                                		if (child2.containsKey("core")) 
                                        {
                                        	JSONObject core = child2.getJSONObject("core");
                                            JSONArray cp = new JSONArray();
                                            cp.add(core.getString("lng"));
                                            cp.add(core.getString("lat"));
                                            child2.put("cp", cp);
                                            child2.remove("core");
                        				}
									}
                                }
							}
                        }
					}
                }
//                System.out.println(data.toJSONString());
                
                //path = target + path.replace(source, "");
                
                String path2 = new File(path).getPath();
                String source2 = new File(source).getPath();
                String target2 = new File(target).getPath();
                path2 = target2 + path2.replace(source2, "");
                
                FileUtils.writeStringToFile(new File(path2), data.toJSONString(), "UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
		}
    	
    }
    
    //递归获取指定路径下的所有文件和文件夹路径
    private static List<String> recursion(String path)
    {
    	List<String> paths = new ArrayList<String>();
    	File file = new File(path);
    	//路径是否存在，是否为文件夹
    	if (!file.exists()&&!file.isDirectory()) 
    	{
    		return paths;
		}
    	File[] files = file.listFiles();
    	//是否有文件或文件夹，在递归得到文件夹下的文件和文件夹
    	for (int i = 0; i < files.length; i++) 
        {
        	file = files[i];
        	if(file.isFile())
        	{
        		paths.add(file.getPath());
        	}
        	if (file.isDirectory()) 
        	{
				List<String> childs = recursion(file.getPath());
				if(childs!=null&&childs.size()>0)
				{
					paths.addAll(childs);
				}
			}
		}
    	return paths;
    }
    
    private static Object parse(Object object)
    {
        Object response = null;
        if(object == null){}
        else if(object instanceof JSONObject){
            JSONObject jsonObj = (JSONObject) object;
            for (Map.Entry<String, Object> entry : jsonObj.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                if(StringUtils.isBlank(key)) {continue;}
                //如果找到key,则中断循环,返回结果.
                if(key.indexOf("core")>-1)
                {
                    response = value;
                    JSONObject core = jsonObj.getJSONObject("core");
                    JSONArray cp = new JSONArray();
                    cp.add(core.getString("lng"));
                    cp.add(core.getString("lat"));
                    jsonObj.put("cp", cp);
                    jsonObj.remove("core");
                    break;
                }
                //没有找到,则找其子是否对应key.
                if(value!=null)
                {
                    Object child = parse(value);
                    if(child!=null)
                    {
                        response = child;
                        break;
                    }
                }
            }
        }else if(object instanceof JSONArray){
            JSONArray jsonAry = (JSONArray) object;
            for(int i = 0; i < jsonAry.size(); i++) {
                Object data = parse(jsonAry.get(i));
                if(data!=null)
                {
                    response = data;
                    break;
                }
            }
        }else {}
        return response;
    }
    
    // 读取json文件
    private static final JSONArray read(String path)
    {
        JSONArray datas = new JSONArray();
        try {
            //读取本地json文件，转为json集合
            String fastjson=FileUtils.readFileToString(new File(path), "UTF-8");
            datas = JSON.parseArray(fastjson);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return datas;
    }
    
    // 写入json文件
    private static final void write(String path, String datas)
    {
        try {
            //json集合生成本地json文件
            FileUtils.writeStringToFile(new File(path), datas, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}